import random
import pygame
import sys
from pygame.locals import *

class starfield(object):
    def __init__(self, pos , size, max, speed):
        self.stars = []
        self.pos = pos
        self.size = size
        self.max = max
        self.speed = speed
        self.box = True
        self.color = (255,255,255)
        self.bordercolor = Color(255,255,255)
        self.backgroundcolor = Color(0,0,0)
        for loop in range(0, max):
            star = [random.randrange(0, size[0] - 1),
                    random.randrange(0, size[1] - 1)]
            self.stars.append(star);
    def draw(self, screen):
        if self.box:
             pygame.draw.rect(screen, self.backgroundcolor, Rect(self.pos[0], self.pos[1], self.size[0],self.size[1]), 0)
             pygame.draw.rect(screen, self.bordercolor, Rect(self.pos[0], self.pos[1], self.size[0],self.size[1]), 1)
        for loop in range(0, self.max):
            p = (self.pos[0] + self.stars[loop][0], self.pos[1] + self.stars[loop][1] )
            screen.set_at(p, self.color)
    def update(self):
        for loop in range(0, self.max):
            self.stars[loop] = (self.stars[loop][0] + self.speed, self.stars[loop][1])
            if self.stars[loop][0]>self.size[0]:
                self.stars[loop] = (0, self.stars[loop][1])
            
# DEMO
sf = [starfield( (50,50), (550,410), 80, 1 ),       
      starfield( (80,150), (200,200), 33, 2 ),
      starfield( (380,150), (200,200), 33, 3 ),
      starfield( (5,5), (80,80), 12, 4 )
      ]

sf[1].color = (255,0,0)
sf[2].color = (0,255,0)
sf[3].color = (0,0,255)


TIMEREVENT = pygame.USEREVENT
UPDATEEVENT = pygame.USEREVENT+1
FPS = 50
pygame.init()
window = pygame.display.set_mode((640, 480))

background = None
background = pygame.Surface(window.get_size())
background.fill((0, 0, 0))

pygame.time.set_timer(TIMEREVENT, int(1000 / FPS))
pygame.time.set_timer(UPDATEEVENT, 50)

while True:

    for event in pygame.event.get():
        if event.type == TIMEREVENT:
            background.fill((0,0,0))
            for s in sf:
                s.draw(background)
            window.blit(background, (0, 0))
            pygame.display.flip()
        elif event.type == UPDATEEVENT:
            for s in sf:
                s.update()
            # Move starfield
            x = sf[3].pos[0] + 2
            y = sf[3].pos[1] + 2
            if x>640: x=-50
            if y>480: y=-40
            sf[3].pos = (x,y)

        elif event.type == pygame.QUIT:
            sys.exit()
